/**
* @package Scribble
*/

/**
* Init UI
*/
$(document).ready(function() {

	// Create columns from the Page tree
	initPageColumns();

	/*// Add handlers for all "delete" links
	$('a[rel="delete"]').click(function() {

		// Confirm
		if(!confirm("Are you sure you want to remove this page\nand all sub-pages?")) {
			return false;
		}

		// Disable sorting, send request
		$('.titlebar').addClass('busy');
		$('table.list tbody').sortable('disable')
		$.post(this.href, {method:'delete'}, doDeleteComplete);

		// Cancel bubbling
		return false;
	});*/
});

/**
* Builds the expanding-columns UI for traversing through the Pages.
*
* @return void
*/
function initPageColumns() {

	// Create a container into which the page columns will live, and hide the
	// original Page tree
	var pagesUl = $('#pages').hide();
	$('<div id="page-column-container"></div>').insertAfter(pagesUl);

	// Create a container where removed-columns can live
	$('<div id="page-column-bin"></div>').insertAfter(pagesUl).hide();

	// Traverse the Page tree, adding columns as they're found
	addPageColumn(pagesUl);
	expandPageColumn(pagesUl);
}

/**
* Add a new tree of Pages (ul) to the specified container, and create a
* column element that will represent the nodes in that tree.
*
* @param HtmlElement UL element to add to the tree
* @param HtmlElement LI to which the UL element will be added
* @return void
*/
function addPageColumn(ul, parentLi) {

	// Attach the UL to it's parent LI, if specified
	if(parentLi) {
		ul.appendTo(parentLi);
	}

	// Build the column that will be injected into the container upon expansion.
	// If a column has already been created for "ul", then no need to repeat.
	if(!ul.data('column')) {
		var col = $('<ul class="column"></ul>').data('ul', ul);
		ul.children('li').each(function() {
	
			// Create a node in the column, based on the LI node in the original UL
			// element.
			var li = $(this);
			var pageData = $.evalJSON($(this).children('input[rel=data]').val());
			var node = $('<li id="pageid_'+pageData.id+'"></li>');

			// Sorter (adjusts the weight of this Page amongst it's siblings)
			var aSorter = $('<a class="sorter" title="Drag to reorder this page"><span>&#10208;</span></a>').appendTo(node);

			// Toggle (expand/collapse children)
			if(pageData._childcount>0) {
				var aToggle = li.children('a[class=toggle]').appendTo(node).click(togglePageChildren);
			}

			// Edit link
			var dEditWrap = $('<div class="edit-wrap"></div>').appendTo(node);
			var aEdit = li.children('a[class=edit]').appendTo(dEditWrap);

			// Meta information (publish status, etc)
			var dMetaWrap = $('<div class="meta-wrap"></div>').appendTo(node);
			if(pageData._ispublished!=1) {
				var sNotPublished = $('<span class="not-published">Not Published</span>').appendTo(dMetaWrap);
			}
			if(pageData._hasexpired==1) {
				var sHasExpired = $('<span class="has-expired">Expired</span>').appendTo(dMetaWrap);
			}
			if(pageData.isindex==1) {
				var sIsIndex = $('<span class="is-index">Homepage</span>').appendTo(dMetaWrap);
			}

			// Store references and add the node to the column
			node.data('li', li);
			li.data('columnNode', node);
			node.appendTo(col);
	
			// If this node itself contains a non-empty <ul> element, then create a
			// column for that too
			var childUl = li.children('ul');
			if(childUl.size()>0) {
				addPageColumn(childUl);
			}
		});

		// Make the nodes sortable
		col.sortable({
			axis: 'y',
			handle: 'a.sorter',
			items: 'li',
			opacity: 0.5,
			update: function(ev, ui) {
				var params = $(this).sortable('serialize');
				//$(this).sortable('disable');
				//$('.titlebar').addClass('busy');
				$.post(Buan.UrlCommand.createUrl('scribble', 'page', 'reorder'), params, doWeightSaveComplete);
			}
		});

		// Store a reference to this column in the real UL it represents
		ul.data('column', col);
	}
}

/**
* Load and display the Pages within the specified column.
*
* @param HtmlElement The UL node in the hidden tree
* @return void
*/
function expandPageColumn(ul) {

	// If the column is already expanded, don't continue
	if(ul.hasClass('expanded')) {
		return;
	}
	ul.addClass('expanded');
	var li = ul.parent('li');

	// Determine the depth at which the UL node appears in it's tree and remove any
	// other columns that are already open in that same depth, or higher
	var depth = ul.parents('ul').size();
	var columns = $('#page-column-container ul');
	var bin = $('#page-column-bin');
	if(depth>0 && columns.size()>depth) {
		$(columns[depth-1]).children('li').removeClass('expanded');
		for(var i=depth; i<columns.size(); i++) {
			var c = $(columns[i]);
			var cUl = c.data('ul');
			cUl.removeClass('expanded');
			c.children('li').removeClass('expanded');
			$(columns[i]).appendTo(bin);
		}
	}

	// Resize all existing columns in order to fit the new one
	if(depth>0) {
		columns = $('#page-column-container ul');
		var node = li.data('columnNode');
		node.addClass('expanded');
		var cWidth = Math.floor($('#page-column-container').width()/(columns.size()+1));
		columns.animate({width: cWidth}, function() {
			var col = ul.data('column');
			var container = $('#page-column-container');
			col.width(cWidth).hide().addClass('col-depth-'+depth).appendTo(container).fadeIn('fast');
		});
	}
	else {
		// Draw the column to the next available space in the container
		var col = ul.data('column');
		if(col) {
			var container = $('#page-column-container');
			col.addClass('col-depth-0').appendTo(container);
		}
	}
}

/**
* Hide the specified column.
*
* @param HtmlElement The UL node in the hidden tree
* @return void
*/
function collapsePageColumn(ul) {

	// Remove the column, and any column in a higher depth, from the container
	var depth = ul.parents('ul').size();
	var columns = $('#page-column-container ul');
	var bin = $('#page-column-bin');
	for(var i=depth; i<columns.size(); i++) {
		var c = $(columns[i]);
		var cUl = c.data('ul');
		cUl.removeClass('expanded');
		c.children('li').removeClass('expanded');
		$(columns[i]).appendTo(bin);
	}
	var node = ul.parent('li').data('columnNode');

	// Resize all existing columns to fill the container
	if(depth>0) {
		columns = $('#page-column-container ul');
		node.removeClass('expanded');
		var cWidth = Math.floor($('#page-column-container').width()/(columns.size()));
		columns.animate({width: cWidth});
	}
	else {
		$('#page-column-container ul').css('width', '100%');
		node.removeClass('expanded');
	}
}

/**
* Loads any child Pages of the column that has been opened, and inserts them
* as a new page column.
*
* @param Event Fired from clicking the toggle link
* @param bool false
*/
function togglePageChildren(ev) {

	// If the node already contains a UL element, then no need for loading data
	// from the server.
	ev.currentTarget.blur();
	var li = $(ev.currentTarget).parent('li').data('li');
	var ul = li.children('ul');
	if(ul.size()>0) {
		if(ul.hasClass('expanded')) {
			collapsePageColumn(ul);
		}
		else {
			expandPageColumn(ul);
		}
		return false;
	}

	// Load the children
	$.get($(ev.currentTarget).attr('href'), function(response) {

		// Create a tree from the response
		var pages = $.evalJSON(response);
		var elUl = $('<ul></ul>');
		for(var i=0; i<pages.length; i++) {
			var p = pages[i];
			var elLi = $('<li></li>').appendTo(elUl);
			var elData = $('<input rel="data" type="hidden" value="" />').val($.toJSON(p)).appendTo(elLi);
			var elAEdit = $('<a href="'+Buan.UrlCommand.createUrl('scribble', 'page', p.id)+'" class="edit"></a>').html(p.name).appendTo(elLi);
			if(p._childcount>0) {
				var elAToggle = $('<a href="'+Buan.UrlCommand.createUrl('scribble', 'page', {p:p.id})+'" class="toggle"><span>(subpages)</span></a>').appendTo(elLi);
			}
		}

		// Add the column
		addPageColumn(elUl, li);
		expandPageColumn(elUl);
	});

	// Prevent bubbling
	return false;
}

/**
* Triggered after the weightings have been saved to the server.
*
* @return void
*/
function doWeightSaveComplete() {
	//$('.titlebar').removeClass('busy');
	//$('table.list tbody').sortable('enable');
}

/**
* Triggered after a page is successfully removed from the system.
*
* @param string Response from the server
* @param
* @return void
*/
function doDeleteComplete(response, status) {

	// Remove the row
	$('#pageid_'+response).remove();

	// Re-enable sorting
	$('.titlebar').removeClass('busy');
	$('table.list tbody').sortable('refresh');
	$('table.list tbody').sortable('enable');
}